<template>
	<div id="normalListDiv">
		<el-tabs v-model="activeTabsName" @tab-click="handleChangeTab">
			<el-tab-pane label="详细列表" name="agentList">
				<div id="searchDiv" v-if="formData.agentStatus == 1">
					<!-- 搜索条件 -->
					<el-form :model="formData" :inline="true" :label-width="100">
						<el-form-item label="异常来源" prop="wrongStatus">
							<yd-select
								v-model="formData.wrongStatus"
								:config="{
									placeholder: '请选择异常来源',
									data: [
										{ value: 1, label: '重启' },
										{ value: 2, label: '丢包率' },
										{ value: 3, label: 'CPU使用率' },
										{ value: 4, label: '内存使用率' },
										{ value: 5, label: '磁盘使用率' },
									],
									selectKey: 'value',
									allOption: true,
									multiple: false,
								}"
							></yd-select>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
						</el-form-item>
					</el-form>
				</div>
				<!--查询列表-->
				<YdTable
					:formData="formData"
					:tableConfig="tableConfig"
					:tableData="tableData.data"
					ref="multipleTable"
					@sizeChangeHandler="queryGrid"
					@currentChangeHandler="queryGrid"
					@sortChangeHandler="queryGrid"
				>
				</YdTable>
			</el-tab-pane>

			<el-tab-pane label="历史曲线图" name="historyLine">
				<div id="histotySearchDiv">
					<!-- 搜索条件 -->
					<el-form :model="lineFormData" :inline="true" :label-width="100">
						<el-form-item label="时间范围" name="timeRange">
							<yd-time-range
								:config="{
									defaultValue: 'today',
								}"
								:shortcutsKey="['today', 'last10m', 'last1h']"
								@pickChange="handlePickChange"
							>
							</yd-time-range>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" icon="Search" @click="queryMap">查 询</el-button>
						</el-form-item>
					</el-form>
				</div>
				<!--图表-->
				<el-row>
					<div class="chart-item" ref="lostHistoryLineRef"></div>
				</el-row>
				<el-row>
					<div class="chart-item" ref="speedHistoryLineRef"></div>
				</el-row>
			</el-tab-pane>
		</el-tabs>

		<!--详情-->
		<el-dialog
			:title="title"
			v-model="open.detailDialog"
			width="1300px"
			append-to-body
			center
			@close="cancelDetailHandle"
			:close-on-click-modal="false"
		>
			<div>
				<div id="alarmDialogScrollbar" style="height: 550px">
					<el-scrollbar style="height: 100%">
						<el-form ref="detailFormRef" :model="detailForm" label-width="150px">
							<el-row>
								<el-col :span="8">
									<el-form-item label="Agent IP:" prop="agentIp">
										{{ detailForm.agentIp }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="别名:" prop="aliasName">
										{{ detailForm.aliasName }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="计算机名:" prop="hostName">
										{{ detailForm.hostName }}
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="8">
									<el-form-item label="采集时间:" prop="lastUpdateTime">
										{{ detailForm.lastUpdateTime }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="入库时间:" prop="createTime">
										{{ detailForm.createTime }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="最后启动时间:" prop="lastLaunchTime">
										{{ detailForm.lastLaunchTime }}<span class="lastLaunchTimeSpan" @click="getHistoryRebootTimeHandle()">(历史启动时间)</span>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="8">
									<el-form-item label="抓包口个数:" prop="ethCount">
										{{ detailForm.ethCount }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="网口名:" prop="capturePort">
										{{ detailForm.capturePort }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="流量:" prop="captureSpeed"> {{ detailForm.captureSpeed }}bps </el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="8">
									<el-form-item label="抓包总数:" prop="minuteCaptureCount">
										{{ detailForm.minuteCaptureCount }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="抓包丢包总数:" prop="minuteCaptureLostCount">
										{{ detailForm.minuteCaptureLostCount }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="丢包率:" prop="minuteCaptureLostRate"> {{ detailForm.minuteCaptureLostRate }}% </el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="8">
									<el-form-item label="发送速率(bps):" prop="sendSpeed">
										{{ detailForm.sendSpeed }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="发送数据压缩比:" prop="compressRate">
										{{ detailForm.compressRate }}
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="抓包队列丢包总数:" prop="minuteQueueLostCount">
										{{ detailForm.minuteQueueLostCount }}
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="8">
									<el-form-item label="CPU使用率:" prop="cpuRate"> {{ detailForm.cpuRate }}% </el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="内存使用率:" prop="memoryRate"> {{ detailForm.memoryRate }}% </el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="磁盘使用率:" prop="diskRate"> {{ detailForm.diskRate }}% </el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<el-form-item label="阀值:" prop="agentThreshold">
										{{ detailForm.agentThreshold }}
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<el-form-item label="不监控的磁盘分区:" prop="removeDiskPartition">
										{{ detailForm.removeDiskPartition }}
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<el-form-item label="磁盘使用率明细:" prop="allDiskInfo" style="word-wrap: break-word">
										{{ detailForm.allDiskInfo }}
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</el-scrollbar>
				</div>
			</div>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="cancelDetailHandle">关 闭</el-button>
			</template>
		</el-dialog>

		<!--详情-->
		<el-dialog
			:title="historyTimeTitle"
			v-model="open.historyTimeDialog"
			width="500px"
			append-to-body
			center
			@close="cancelHistoryTimeHandle"
			:close-on-click-modal="false"
		>
			<div>
				<div id="alarmDialogScrollbar" style="height: 400px">
					<el-scrollbar style="height: 100%">
						<!--查询列表-->
						<YdTable
							:formData="historyTimeFormData"
							:tableConfig="historyTimeTableConfig"
							:tableData="historyTimeTableData.data"
							ref="multipleTable"
							@sizeChangeHandler="getHistoryRebootTimeHandle"
							@currentChangeHandler="getHistoryRebootTimeHandle"
							@sortChangeHandler="getHistoryRebootTimeHandle"
						>
						</YdTable>
					</el-scrollbar>
				</div>
			</div>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="cancelHistoryTimeHandle">关 闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="NormalAgentList" lang="tsx">
import { reactive, onMounted, ref, onUnmounted, onActivated, onDeactivated, watch } from 'vue';
import { useRoute } from 'vue-router';
import {
	getAgentShowList,
	lostHistoryLine,
	speedHistoryLine,
	getAgentDetail,
	getHistoryRebootTime,
} from '@/api/management/selfMonitoring/agentStatusMonitoring';
import * as echarts from 'echarts';
import useAppStore from '@/store/modules/app';
import { noDataOption } from '@/utils/chartNoData';
import { parseTime } from '@/utils/common';
import useCurrentInstance from '@/utils/useCurrentInstance';

const { proxy } = useCurrentInstance();
const route = useRoute();
const appStore = useAppStore();

//标题
const title = ref('');
//历史启动时间标题
const historyTimeTitle = ref('');
//弹出框
let open = reactive<anyObj>({
	detailDialog: false,
	historyTimeDialog: false,
});
//详细表单
let detailForm = ref<anyObj>({});
//tabs标签默认显示
const activeTabsName = ref('agentList');
//图表
let chart: anyObj = {
	lostHistoryLine: null,
	speedHistoryLine: null,
};
// 搜索表单数据
let formData = reactive<anyObj>({
	...route.query,
	pageNum: 1,
	pageSize: 10,
});
let lineFormData = reactive<anyObj>({
	...route.query,
});
// 列表配置
let tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: 'Agent IP',
			prop: 'agentIp',
			width: 90,
		},
		{
			label: '别名',
			prop: 'aliasName',
		},
		{
			label: '状态',
			prop: 'agentStatus',
			width: 60,
			formatter(row, val) {
				// Agent状态：0正常；1异常；2断采
				if (val == 0) {
					return '正常';
				} else if (val == 1) {
					return '异常';
				} else {
					return '断采';
				}
			},
		},
		{
			label: '采集时间',
			prop: 'lastUpdateTime',
			width: 160,
		},
		{
			label: '重启',
			prop: 'rebootFlag',
			width: 60,
			renderXss: (row, val) => {
				if (val == 0) {
					return <span>否</span>;
				} else {
					return <span style="color: red;">是</span>;
				}
			},
		},
		{
			label: '重启总次数',
			prop: 'rebootCount',
			width: 100,
		},
		{
			label: '丢包率',
			prop: 'minuteCaptureLostRate',
			width: 80,
			renderXss: (row, val) => {
				if (row.minuteCaptureCount != null && row.minuteCaptureCount != 0) {
					var rate = Math.round((row.minuteCaptureLostCount / (row.minuteCaptureCount + row.minuteCaptureLostCount)) * 10000) / 100 + '%';
					if (row.wrongStatus == 2) {
						return <span style="color: red;">{rate}</span>;
					} else {
						return <span>{rate}</span>;
					}
				}
				return <span>0%</span>;
			},
		},
		{
			label: 'CPU使用率',
			prop: 'cpuRate',
			width: 100,
			renderXss: (row, val) => {
				var rate = Math.round((row.cpuRate / 10000) * 10000) / 100 + '%';
				if (row.wrongStatus == 3) {
					return <span style="color: red;"> {rate}</span>;
				} else {
					return <span>{rate}</span>;
				}
			},
		},
		{
			label: '内存使用率',
			prop: 'memoryRate',
			width: 100,
			renderXss: (row, val) => {
				var rate = Math.round((row.memoryRate / 10000) * 10000) / 100 + '%';
				if (row.wrongStatus == 4) {
					return <span style="color: red;">{rate}</span>;
				} else {
					return <span>{rate}</span>;
				}
			},
		},
		{
			label: '磁盘使用率',
			prop: 'diskRate',
			width: 100,
			renderXss: (row, val) => {
				var rate = Math.round((row.diskRate / 100) * 10000) / 100 + '%';
				if (row.wrongStatus == 5) {
					return <span style="color: red;">{rate}</span>;
				} else {
					return <span>{rate}</span>;
				}
			},
		},
		{
			label: '入库时间',
			prop: 'createTime',
			width: 160,
		},
		{
			label: '网口名',
			prop: 'capturePort',
		},
		{
			label: '抓包总数',
			prop: 'minuteCaptureCount',
			width: 80,
		},
		{
			label: '操作',
			prop: '',
			width: 100,
			operation: [
				{
					text: '详情',
					handler: (scope) => jumpToAgentDetailHandle(scope.row),
				},
			],
		},
	],
	// 开启复选框
	enableSelection: false,
	// 开启分页
	pagination: {
		pageNum: 1,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = reactive({
	data: [],
});
// 查询历史启动时间表单数据
let historyTimeFormData = reactive<FormModelType>({
	...route.query,
	pageNum: 1,
	pageSize: 20,
});
// 列表配置
let historyTimeTableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '时间',
			prop: 'lastLaunchTime',
			width: 200,
		},
	],
	// 开启复选框
	enableSelection: false,
	// 加载层
	loading: true,
});
// 列表数据
let historyTimeTableData = reactive({
	data: [],
	total: 0,
});
// 图形自适应
const activatedFlag = ref(false);

onMounted(() => {
	searchHandler();
	initCharts();
	activatedFlag.value = true;
	// 添加resize监听器,自适应图表大小
	window.addEventListener('resize', chartResize);
	queryMap();
});
onUnmounted(() => {
	// 销毁resize监听器
	window.removeEventListener('resize', chartResize);
});
onActivated(() => {
	activatedFlag.value = true;
	chartResize();
});
onDeactivated(() => {
	activatedFlag.value = false;
});
// 监听侧边栏收缩展开状态
watch(
	() => appStore.sidebar.opened,
	() => {
		if (activatedFlag.value) {
			setTimeout(() => {
				chartResize();
			}, 250);
		}
	}
);

function handlePickChange(val: any) {
	lineFormData.startTime = val[0];
	lineFormData.endTime = val[1];
}

// 搜索
function searchHandler() {
	formData.pageNum = 1;
	queryGrid();
}
//查询列表数据
function queryGrid() {
	tableConfig.loading = true;
	getAgentShowList(formData).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			tableConfig.loading = false;
			return;
		}
		tableConfig.loading = false;
		tableData.data = res.data.data;
		tableConfig.pagination!.total = res.data.total;
	});
}
// tab页切换
function handleChangeTab() {
	if (activeTabsName.value === 'historyLine') {
		setTimeout(() => {
			chartResize();
		}, 100);
	}
}
/**
 * 初始化
 */
function initCharts() {
	chart.lostHistoryLine = echarts.init(proxy.$refs.lostHistoryLineRef);
	chart.speedHistoryLine = echarts.init(proxy.$refs.speedHistoryLineRef);
}
// 重新设置图表宽高
function chartResize() {
	Object.keys(chart).forEach((key) => {
		chart[key].resize();
	});
}
/**
 * 图表配置项
 * @param myChart 图表
 * @param mapData 图表数据
 * @param title 图表标题
 */
function setOption(myChart: any, mapData: any, timeList: any, title: any, legendData: any) {
	myChart.clear();
	if (timeList != null && timeList.length > 0) {
		myChart.setOption({
			title: {
				text: title,
				textStyle: {
					color: '#000000',
				},
				top: 50,
				left: 83,
			},
			tooltip: {
				trigger: 'axis',
				//设置tooltip超出画布时
				/*confine: true,*/
				position: function (p: any) {
					//画布的宽度：实现当鼠标位置小于画布宽度一半时，在右侧，否则在左侧
					const chartsWidth = 1800;
					if (p[0] < chartsWidth / 2) {
						p[0] = p[0];
					} else {
						p[0] = p[0] - 130;
					}
					return [p[0], p[1]];
				},
				formatter: function (params: any) {
					let content = params[0].name;
					if (title == '丢包率大小') {
						params.forEach((p: any) => {
							content += '<br/>' + p.marker + p.seriesName + ' : ' + parseFloat(p.value).toFixed(2) + '%';
						});
					} else {
						params.forEach((p: any) => {
							if (p.value > 1000000) {
								content += '<br/>' + p.marker + p.seriesName + ' : ' + (p.value / 1000000).toFixed(2) + 'Mbps';
							} else if (p.value > 1000) {
								content += '<br/>' + p.marker + p.seriesName + ' : ' + (p.value / 1000).toFixed(2) + 'Kbps';
							} else {
								content += '<br/>' + p.marker + p.seriesName + ' : ' + p.value + 'bps';
							}
						});
					}
					return content;
				},
			},
			color: ['#3DBDE4', '#FA660A', '#8923F1', '#FF0000', '#339966', '#C013E4', '#85E432'],
			legend: {
				data: legendData,
				type: 'scroll',
				itemWidth: 20,
				itemGap: 10,
				top: 50,
				left: mapData.length <= 4 ? 'center' : undefined,
				right: mapData.length > 4 ? 20 : undefined,
				icon: 'roundRect',
				textStyle: {
					color: 'black',
				},
				width: '75%',
			},
			// 坐标系位置
			grid: {
				x: 100,
				y: 100,
				x2: 50,
			},
			xAxis: {
				type: 'category',
				data: timeList,
			},
			yAxis: {
				type: 'value',
				axisLabel: {
					formatter: function (value: any) {
						let labStr = '';
						if (title == '丢包率大小') {
							labStr = value + '%';
						} else {
							if (value > 1000000) {
								labStr = (value / 1000000).toFixed(0) + 'Mbps';
							} else if (value > 1000) {
								labStr = (value / 1000).toFixed(0) + 'Kbps';
							} else {
								labStr = value + 'bps';
							}
						}
						return labStr;
					},
				},
			},
			series: mapData,
		});
	} else {
		noDataOption(myChart, {
			text: title,
			textStyle: {
				color: '#000000',
			},
			top: 20,
			left: 40,
		});
	}
}
/**
 * 表格数据查询
 */
function queryMap() {
	let start = lineFormData.startTime;
	let end = lineFormData.endTime;
	//点击自定义的时候将清理startTime和endTime
	if (start == null || end == null) {
		proxy.$modal.msgWarning('开始和结束时间不能为空');
		return;
	} else {
		//最近一小时跨天问题，以结束时间，如果最近一小时存在跨天，比如当前时间为2020-11-05 00:08:00，
		// 那么startTime="2020-11-05 00:00:00"  endTime="2020-11-05 00:08:00"。
		let startFormat = parseTime(start, '{y}-{m}-{d}');
		let startHmsFormat = parseTime(start, '{h}:{i}:{s}');
		let endFormat = parseTime(end, '{y}-{m}-{d}');
		let endHmsFormat = parseTime(end, '{h}:{i}:{s}');
		var endTime = new Date(end);
		var sumTime = endTime.getHours() + endTime.getMinutes() + endTime.getSeconds();
		var old_time = new Date(endFormat.replace(/-/g, '/'));
		var new_time = new Date(old_time.getTime() - 24 * 3600 * 1000);
		var new_format = parseTime(new_time, '{y}-{m}-{d}');
		if (startFormat != endFormat && (startFormat != new_format || sumTime != 0)) {
			proxy.$modal.msgWarning('开始和结束时间不能跨天');
			return;
		}
	}
	lostHistoryLine(lineFormData).then((res: ApiResponse) => {
		const lineVo = res.data;
		let seriesData = [];
		if (lineVo != null && lineVo.subList != null && lineVo.subList.length > 0) {
			for (let i = 0; i < lineVo.subList.length; i++) {
				const item = lineVo.subList[i];
				let temp = {
					type: 'line',
					name: item.name,
					data: item.data,
				};
				seriesData.push(temp);
			}
		}
		setOption(chart.lostHistoryLine, seriesData, lineVo.timeList, '丢包率大小', lineVo.legendList);
	});
	speedHistoryLine(lineFormData).then((res: ApiResponse) => {
		const lineVo = res.data;
		let seriesData = [];
		if (lineVo != null && lineVo.subList != null && lineVo.subList.length > 0) {
			for (let i = 0; i < lineVo.subList.length; i++) {
				const item = lineVo.subList[i];
				let temp = {
					type: 'line',
					name: item.name,
					data: item.data,
					smooth: true,
				};
				seriesData.push(temp);
			}
		}
		setOption(chart.speedHistoryLine, seriesData, lineVo.timeList, '抓包口流量大小', lineVo.legendList);
	});
}
//关闭agent详细处理方法
function cancelDetailHandle() {
	open.detailDialog = false;
}
//跳转至详情页面
function jumpToAgentDetailHandle(row: any) {
	title.value = 'Agent状态详情';
	getAgentDetail({
		id: row.id,
		agentIp: row.agentIp,
	}).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			return;
		}
		let agentVo = res.data;
		let minuteCaptureLostRate = 0;
		if (agentVo.minuteCaptureCount != null && agentVo.minuteCaptureCount != 0) {
			minuteCaptureLostRate =
				Math.round((agentVo.minuteCaptureLostCount / (agentVo.minuteCaptureCount + agentVo.minuteCaptureLostCount)) * 10000) / 100;
		}
		agentVo.minuteCaptureLostRate = minuteCaptureLostRate;
		let cpuRate = Math.round((agentVo.cpuRate / 10000) * 10000) / 100;
		agentVo.cpuRate = cpuRate;
		let memoryRate = Math.round((agentVo.memoryRate / 10000) * 10000) / 100;
		agentVo.memoryRate = memoryRate;
		let diskRate = Math.round((agentVo.diskRate / 100) * 10000) / 100;
		agentVo.diskRate = diskRate;
		detailForm.value = agentVo;
	});
	open.detailDialog = true;
}
//查询历史启动时间
function getHistoryRebootTimeHandle() {
	historyTimeTableConfig.loading = true;
	getHistoryRebootTime({
		agentIp: historyTimeFormData.agentIp,
	}).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			historyTimeTableConfig.loading = false;
			return;
		}
		historyTimeTableConfig.loading = false;
		historyTimeTableData.data = res.data;
		historyTimeTableData.total = 100;
	});
	historyTimeTitle.value = '历史启动时间';
	open.historyTimeDialog = true;
}
//关闭历史启动时间弹出框
function cancelHistoryTimeHandle() {
	open.historyTimeDialog = false;
}
</script>

<style lang="scss" scoped>
.container {
	margin: 10px;
}

.chart-item {
	width: 100%;
	height: 350px;
}
</style>

<style>
/*给日期选中间隔设置样式*/
#histotySearchDiv .el-col-2 {
	width: 85px;
}

/*给日期选中设置样式*/
#histotySearchDiv .el-link--inner {
	/*background-color: #06cbcb !important;*/
	padding-top: 5px;
	width: 80px;
	height: 25px;
	font-size: 15px;
	text-align: center;
	color: #1b2c5d;
}

/*给选中后的选择框设置样式*/
#histotySearchDiv .option-active {
	background-color: #06cbcb !important;
	border-radius: 2px;
	color: white !important;
}

/*设置时间靠左*/
#histotySearchDiv .temp-search-form-item {
	margin-left: 20px;
}

/*给“日期”设置样式*/
#histotySearchDiv .el-range-editor--mini {
	background-color: #bfcbd9;
}

/*给“日期”时钟设置样式*/
#histotySearchDiv .el-icon-time {
	color: white;
}

/*给日期设置样式*/
#histotySearchDiv .temp-item-time-range .el-date-editor .el-range-input {
	/*color: #1b2c5d !important;*/
	color: white;
	border: 1px;
	height: 25px;
}

/*给日期里面的至*/
#histotySearchDiv .temp-item-time-range .el-date-editor .el-range-separator {
	padding-top: 4px;
	color: white !important;
	font-size: 13px;
}

/*详情里面最后重启时间 样式*/
#alarmDialogScrollbar .lastLaunchTimeSpan {
	text-decoration: underline;
	cursor: pointer;
	/*color: rgb(255, 154, 12);*/
	font-size: 16px;
}

#alarmDialogScrollbar .lastLaunchTimeSpan:hover {
	color: #34b5ff;
}
</style>
